import { getLoadMapList, getTenantID, getUserID, requestFunComponFiex, getUserDepID } from '@/utils';
import { useRequest } from 'umi';
import { ILoadMapTypeAll } from '@/common';
import { useMemo } from 'react';
import { AssetEditManage, AssetMaterialManage, getManageTabSwitch, MyAssetListManageTab } from '../mconfig';
import { getMaterialSearchList } from '../mconfig/UpdateSearchColumns';
import { ManageCommonAPI } from '@/pages/type';
import { getBaseUrl } from '@/services/urlconst';
import { useCallback } from 'react';
import { AssetacquisitionManageAPI } from '../common/type';
import { ManageSearchColumns } from '../mconfig/ModalReadSearchColumns';
import moment from 'moment';
import { message } from 'antd';

const baseUrl = getBaseUrl();
// const baseUrl = '/wenchuang';

/**
 * 资产/材料列表
 * @param curRes
 */
const materialTableService = (
  curRes: Record<string, any>,
  type: number, //type 0:材料 1:资产
  queryType: string, //queryType 1:领用 2:退库 3:借用 4:归还
  editState: boolean = false,
  belongID,
  editAssetId?,
) => {
  /**  需要获取的资产类别数据字典 */
  const loadMdicIds: string[] = [`${getTenantID()}${ILoadMapTypeAll.ASSET_TYPE}`, `${getTenantID()}${ILoadMapTypeAll.MATERIAL_TYPE}`];

  /** 获取数据字典loadMdicMap */
  const loadMdicMapObj: Record<string, any> = getLoadMapList(loadMdicIds);

  /** 获取权限参数 */
  let queryTypeObj: Record<string, any> = {};

  // if (editState) {
  //   queryTypeObj = AssetEditManage(curRes);
  // } else {
  //   queryTypeObj = AssetMaterialManage(curRes, queryType);
  // }

  queryTypeObj = AssetMaterialManage(curRes, queryType, type);

  /** 获取列表数据  */
  const { loading, run, refresh, tableProps, data, params } = useRequest(
    (opt: ManageCommonAPI.IGridRequestType) => {
      let requestBody: Record<string, any> = {
        ...queryTypeObj,
        current: 1,
        pageSize: 10,
        sort: 'createTime',
        order: 'desc',
        type,
        assetDepartmentID: belongID,
        ...opt,
      };

      let requestURL;

      if (queryType == '1' || queryType == '3') {
        // 领用时-资产模态框请求数据接口
        if (editState) {
          requestURL = `${baseUrl}/assetInfo/dataGrid/${queryTypeObj?.params}`;
          requestBody.materialId = editAssetId.id ? editAssetId.id : ''; // 当前项的materialId
          requestBody.assetState = `${getTenantID()}${ILoadMapTypeAll.ASSET_STATUS}1001`; // 查询闲置
        } else {
          // if (requestBody.sharing == '0') {
          //   requestBody.createDepartmentID = getUserDepID();
          // }
          if (requestBody.sharing == '3') {
            delete requestBody.sharing;
          }
          if (requestBody.sharing == '2') {
            requestBody.createrID = getUserID(); // 获取当前登录人
            delete requestBody.sharing;
          }
        }
        if (requestBody?.type == 1) {
          requestBody.useType = 1;
          requestBody.assetState = `${getTenantID()}${ILoadMapTypeAll.ASSET_STATUS}1001`;
          requestURL = `${baseUrl}/assetInfo/dataGrid/${queryTypeObj?.params}`;
        } else {
          requestBody.assetState = `${getTenantID()}${ILoadMapTypeAll.MATERIEL_STATUS}1001`; // 查询已入库的
          requestURL = `${baseUrl}/assetMaterial/list/${queryTypeObj?.params}`;
        }
        delete requestBody.total;
      } else {
        // 退库时-资产模态框请求数据接口
        requestBody.assetState = `${getTenantID()}${ILoadMapTypeAll.ASSET_STATUS}1000`; // 查询在用
        if (requestBody?.type == 1) {
          //资产
          delete requestBody?.type;
          requestURL = `${baseUrl}/assetInfo/dataGrid/${queryTypeObj?.params}`;
        } else {
          //材料
          delete requestBody?.type;
          requestBody.residueNum = 1;
          requestURL = `${baseUrl}/assetStuff/dataGrid/${queryTypeObj?.params}`;
        }
      }
      return requestFunComponFiex('POST', requestURL, requestBody);
    },
    {
      manual: true, //页面初始请求为 true
      paginated: true,
      defaultPageSize: 10,
    },
  );

  /**  获取管理也数据  */
  const getManageData = (otherRequest: ManageCommonAPI.IGridRequestType | any) => {
    const request: ManageCommonAPI.IGridRequestType | any = {
      ...otherRequest,
    };
    run({ ...request });
  };

  /** 搜索表单 */
  const searchList: any = getMaterialSearchList({ ...loadMdicMapObj, curRes }, type, queryType, belongID);

  /** 页面列表 */
  const returnTableProps = useMemo(() => {
    return {
      data,
      pagination: tableProps?.pagination,
      params: params?.[0],
    };
  }, [data, tableProps]);

  const dataList = useMemo(() => {
    if (data?.rows?.length) {
      return data?.rows?.map((item) => {
        item.supplier = item?.assetjson?.supplier;
        return item;
      });
    } else {
      return [];
    }
  }, [data?.rows]);

  return {
    getManageData,
    refreshManage: refresh,
    loading,
    searchList,
    dataList: dataList,
    loadMdicMapObj,
    ...returnTableProps,
  };
};

/**
 * 获取仓库树列表
 * @param getStorageCallback
 * @returns
 */
const getStorageTreeService = (getStorageCallback: (res: any) => void, curRes) => {
  /**获取权限参数 */
  const queryTypeObj: Record<string, any> = getManageTabSwitch(curRes);
  const getStorage = useRequest(
    () => {
      const personUrl = `${baseUrl}/assetStore/treeList/${queryTypeObj.params}`;
      return requestFunComponFiex('POST', personUrl, {
        storeState: 1,
        ...queryTypeObj,
      });
    },
    {
      manual: true,
      onSuccess: (res) => {
        getStorageCallback(res);
      },
    },
  );
  return {
    getStorageRun: getStorage?.run,
    getStorageLoading: getStorage?.loading,
  };
};

/**
 * 获取名下资产
 */
const assetListManageServices = (curRes: Record<string, any>, userID: string) => {
  /***获取数据字典**/
  const loadMdicIds: string[] = [
    `${getTenantID()}${ILoadMapTypeAll.MATERIAL_TYPE}`,
    `${getTenantID()}${ILoadMapTypeAll.ASSET_STATUS}`,
    `${getTenantID()}${ILoadMapTypeAll.ASSET_EQUITY}`,
  ];

  const loadMdicMapObj: Record<string, any> = getLoadMapList(loadMdicIds);

  /**获取权限参数 */
  const queryTypeObj: Record<string, any> = MyAssetListManageTab(curRes);
  /**
   * 获取列表数据
   */
  const { tableProps, data, error, loading, run, params } = useRequest(
    (opt: AssetacquisitionManageAPI.IAssetTableRequestType) => {
      let personUrl = `${baseUrl}/assetInfo/list/${queryTypeObj?.params}`;
      let personBody: any = {
        ...queryTypeObj,
        order: 'desc',
        page: 1,
        rows: 10,
        sort: 'createTime',
        dicTypeIds: loadMdicIds?.toString(), // 字典入参
        assetState: `${getTenantID()}${ILoadMapTypeAll.ASSET_STATUS}1000`, // 查询在用
        ...opt,
        userID,
      };
      return requestFunComponFiex('POST', personUrl, personBody);
    },
    {
      manual: true, //页面初始请求为true
      paginated: true,
      defaultPageSize: 10,
    },
  );

  /* 获取页面数据 */
  const getAssetListTableData = useCallback((otherRequest: AssetacquisitionManageAPI.IAssetTableRequestType | any) => {
    const request: AssetacquisitionManageAPI.IAssetTableRequestType | any = {
      ...otherRequest,
    };
    if (request?.useTime) {
      const [useTimeStart, useTimeEnd] = request.useTime;
      request['useTimeStart'] = useTimeStart.format('YYYY-MM-DD 00:00:00');
      request['useTimeEnd'] = useTimeEnd.format('YYYY-MM-DD 23:59:59');
      delete request['useTime'];
    }
    delete request['useDepartmentFormNameDept'];
    delete request['useDepartmentFormNameUser'];
    if (request['userID']?.length) {
      request['userID'] = request['userID']?.toString();
    } else {
      delete request['userID'];
    }
    // if (request?.assetValue) {
    //   const [assetValueStart, assetValueEnd] = request.assetValue;
    //   request['assetValueMin'] = assetValueStart;
    //   request['assetValueMax'] = assetValueEnd;
    //   delete request['assetValue'];
    // }

    run({
      ...request,
    })?.then((res) => {
      if (res?.msgFlag) {
        message?.success(res?.msg);
      } else {
        message?.warn(res?.msg);
      }
    });
  }, []);

  /** 获取搜索参数 */
  const searchListParams = ManageSearchColumns(loadMdicMapObj, queryTypeObj);

  /* 页面列表 */
  let tableValues = useMemo(() => {
    return {
      assetListData: data,
      pagination: tableProps?.pagination,
    };
  }, [data, tableProps]);

  /***搜索功能配置columns**/
  const searchList = useMemo(() => {
    return {
      searchList: searchListParams,
    };
  }, [loadMdicMapObj?.loadMapInfo]);

  /* 数据字典值  */
  let loadMapList = useMemo(() => {
    return {
      loadMdicMapList: [],
    };
  }, [params]);

  return {
    loading,
    getAssetListTableData, //其他请求操作方法例如刷新等等
    // manageTableParams,
    otherParams: params?.[0],
    ...tableValues, //页面列表值
    ...loadMapList,
    ...searchList,
  };
};

/** 获取子资产数据 */
const assetListChildManageServices = (callback: (res: any) => void) => {
  /**
   * 获取列表数据
   */
  const { tableProps, data, error, loading, run, params } = useRequest(
    (opt: Record<string, any>) => {
      let personUrl = `${baseUrl}/assetInfo/assetChild/${opt.id}`;
      let personBody: any = {
        order: 'desc',
        page: 1,
        rows: 10,
        sort: 'createTime',
        // dicTypeIds: loadMdicIds?.toString(), // 字典入参
        // ...opt,
      };
      return requestFunComponFiex('GET', personUrl, personBody);
    },
    {
      manual: true, //页面初始请求为true
      paginated: true,
      defaultPageSize: 10,
      onSuccess: callback,
    },
  );

  /* 获取页面数据 */
  const getAssetListChildTableData = useCallback((otherRequest) => {
    const request = {
      ...otherRequest,
    };

    run({
      ...request,
    });
  }, []);

  /* 页面列表 */
  let tableValues = useMemo(() => {
    return {
      assetListData: data,
      pagination: tableProps?.pagination,
    };
  }, [data, tableProps]);

  return {
    loading,
    getAssetListChildTableData, //其他请求操作方法例如刷新等等
    // manageTableParams, // 当前搜索参数
    otherParams: params?.[0],
    ...tableValues, //页面列表值
  };
};

export { materialTableService, getStorageTreeService, assetListManageServices, assetListChildManageServices };
